package com.history.common.file;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.history.common.Helpers;
import com.history.common.Logit;
import com.history.dao.ArticleDAO;

public class FileProcess {
	private static final Logit log = Logit.getInstance(FileProcess.class);

	static String fileName = "";
	static String pathBackup = "";
	
	static {
		try {
			fileName = Helpers.getFullPath("UpdateArticles.txt");
			pathBackup = Helpers.getFullPath("backup");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public FileProcess() throws Exception {

	}
	
	public static void write(String line) throws Exception {
		
		File file = new File(fileName);
	    if (!file.exists()) {
	    	file.createNewFile();
	    	file = null;
	    }

		FileOutputStream fos = new FileOutputStream(fileName, true) ;
		OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");
		out.write(line + "\n");
		out.close();
	}

	public static List<String> read() throws Exception {
		List<String> list = new ArrayList<String>();
		try {
		    // Open the file that is the first 
		    // command line parameter
		    FileInputStream fstream = new FileInputStream(fileName);
		    // Get the object of DataInputStream
		    DataInputStream in = new DataInputStream(fstream);
		        BufferedReader br = new BufferedReader(new InputStreamReader(in));
		    String strLine;
		    //Read File Line By Line
		    while ((strLine = br.readLine()) != null)   {
		      // Print the content on the console
		    	if (!StringUtils.isEmpty(strLine)) {
		    		list.add(strLine);
		    	}
		    }
		    //Close the input stream
		    in.close();

		} catch (Exception e) {
			// TODO: handle exception
			log.error(e.getMessage(), e);
		} 
		return list;
	}
	
	public static void move() throws Exception {
		    File inputFile = new File(fileName);
		    File outputFile = new File(pathBackup + File.separator + "UpdateArticles_" +
		    	System.currentTimeMillis() + ".txt");

		    FileReader in = new FileReader(inputFile);
		    FileWriter out = new FileWriter(outputFile);
		    int c;

		    while ((c = in.read()) != -1)
		      out.write(c);

			FileOutputStream fos2 = new FileOutputStream(fileName);
			OutputStreamWriter out2 = new OutputStreamWriter(fos2, "UTF-8");
			out2.write("");
			out2.close();
		    
		    in.close();
		    out.close();
	}
	
	public static void main(String[] args) throws Exception {
		FileProcess.move();
	}
	
}

